package com.jueling.culture.controller;


import com.jueling.culture.compent.RedisComponent;
import com.jueling.culture.core.Result;
import com.jueling.culture.core.ResultGenerator;
import com.jueling.culture.dto.InitDto;
import com.jueling.culture.dto.req.LoginVO;
import com.jueling.culture.model.UserAuthority;
import com.jueling.culture.model.UserInfo;
import com.jueling.culture.service.LoginService;
import com.jueling.culture.service.UserAuthorityService;
import com.jueling.culture.support.annotation.RequiredPermission;
import com.jueling.culture.support.enums.AuthorityCodeEnum;
import com.jueling.culture.util.RedisKeyGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 登录
 * @author linp
 * @create 2022/2/10 11:21
 */
@RestController
public class LoginController {

    @Resource
    private LoginService loginService;
    @Resource
    private UserAuthorityService userAuthorityService;
    @Autowired
    private RedisComponent redisComponent;


    /**
     * 登录
     * @param loginVO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginVO loginVO){
        //登陆
        InitDto initDto = loginService.doLogin(loginVO);
        return ResultGenerator.genSuccessResult(initDto);
    }

    /**
     * 获取用户权限集合
     * @param userId
     * @return
     */
    @GetMapping("/api/sysuser/{userId}")
    @RequiredPermission(authorityCodeEnum = AuthorityCodeEnum.SYSTEM_USER_MANAGE, view = true)
    public Result getUserAuthority(@PathVariable String userId) {
        //获取用户权限集合
        List<UserAuthority> userAuthorityList = userAuthorityService.getUserAuthorityList(userId);
        return ResultGenerator.genSuccessResult(userAuthorityList);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/api/sysuser/logout")
    public Result logout() {
        UserInfo userInfo = UserInfo.currentUser.get();
        redisComponent.remove(RedisKeyGeneratorUtil.accessTokenRedisKeyGenerator(userInfo.getUserName()));
        return ResultGenerator.genSuccessResult();
    }

}
